<template>
	<div class="layout-padding statics-container" ref="container" v-loading="loading">
		<HyCard title="信息统计">
			<HyForm ref="hyFormRef" :hyFormDefault="searchDefault" :hyFormConfig="searchConfig" :hyFormFields="hyFormFields">
				<template #custom>
					<div style="margin-left: 24px">
						<el-button icon="Search" type="primary" :loading="false" @click="getData"> 查询 </el-button>
						<el-button icon="RefreshLeft" style="margin-left: 24px" :loading="false" @click="handleReset"> 重置 </el-button>
					</div>
				</template>
			</HyForm>
			<div class="echart-area">
				<HyCard title="建设层级">
					<div ref="levelRef" class="chart-box"></div>
				</HyCard>
				<HyCard title="应用总投资与应用年度预算">
					<div ref="budgetRef" class="chart-box"></div>
				</HyCard>
				<HyCard title="应用总数量">
					<div class="app-count">
						<p>{{ appTotal }}</p>
						<p>应用总数量</p>
					</div>
				</HyCard>
				<HyCard title="应用资金来源百分比">
					<div ref="sourceRef" class="chart-box"></div>
				</HyCard>
				<HyCard title="应用数量">
					<div ref="appRef" class="chart-box"></div>
				</HyCard>
				<HyCard title="应用领域数量">
					<div ref="domainRef" class="chart-box"></div>
				</HyCard>
			</div>
			<!--  -->
		</HyCard>
	</div>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue';
import HyCard from '/@/components/HyCard/index.vue';
import HyForm from '/@/components/HyForm/index.vue';
import * as echarts from 'echarts';
import { debounce } from 'lodash';
import { getSensitiveCount, treeAndSelf, getSensitiveHierarchy, getSensitiveModeCount } from '/@/api/sensitiveData/statistics';
import { deptTree } from '/@/api/admin/dept';
import { showPopover } from 'v-calendar/dist/types/src/utils/popovers';
export default defineComponent({
	name: 'infoStatistics',
	components: {
		HyCard,
		HyForm,
	},
	setup() {
		const container = ref();
		let loading = ref(false);
		let defaultYear = new Date().getFullYear().toString(); //默认今年
		const searchConfig = computed(() => {
			return {
				span: 8,
				offset: 0,
				labelWidth: '100px',
				type: 'submit',
			};
		});
		const searchDefault = ref({
			year: defaultYear,
		});
		const hyFormFields = ref({
			year: {
				type: 'date',
				picker: 'year',
				label: '年份',
				width: '300px',
				showFormat: 'YYYY',
			},
			responsibleDeptId: {
				type: 'cascader',
				label: '责任部门',
				width: '300px',
				props: {
					checkStrictly: true,
					value: 'id',
					label: 'name',
				},
				options: [],
			},
		});
		let resizeObserver: ResizeObserver;
		const hyFormRef = ref();
		const levelRef = ref();
		const budgetRef = ref();
		const sourceRef = ref();
		const appRef = ref();
		const domainRef = ref();
		let levelChart: any;
		let budgetChart: any;
		let sourceChart: any;
		let appChart: any;
		let domainChart: any;
		function initDomain(data: Array<Object>) {
			//应用领域数量
			domainChart = domainChart || echarts.init(domainRef.value);
			let option = {
				legend: {
					top: 'bottom',
				},
				tooltip: {
					trigger: 'item',
				},
				series: [
					{
						name: '应用领域数量',
						type: 'pie',
						radius: '50%',
						itemStyle: {
							borderRadius: 5,
							borderColor: '#fff',
							borderWidth: 1,
						},
						data: data,
						label: {
							show: true,
							formatter: '{b} {@d}',
						},
					},
				],
			};
			domainChart.setOption(option);
		}
		function initApp(data: Array<Object>) {
			//应用数量
			appChart = appChart || echarts.init(appRef.value);
			let option = {
				legend: {
					top: 'bottom',
				},
				tooltip: {
					trigger: 'item',
					formatter: '{a} <br/>{b} : {c} ({d}%)',
				},
				series: [
					{
						name: '应用数量',
						type: 'pie',
						radius: ['40%', '50%'],
						data: data,
						label: {
							// show: false,
							// position: 'center',
							formatter: '{b}:{@d}',
						},
						// emphasis: {
						// 	//饼图中间显示配置
						// 	label: {
						// 		show: false,
						// 		fontSize: '20',
						// 		fontWeight: 'bold',
						// 		formatter: '{d}%',
						// 	},
						// },
						labelLine: {
							normal: {
								show: true,
							},
						},
					},
				],
			};
			appChart.setOption(option);
		}
		function initSource(data: Array<Object>) {
			//资金来源
			sourceChart = sourceChart || echarts.init(sourceRef.value);
			let option = {
				tooltip: {
					trigger: 'item',
					formatter: '{a} <br/>{b} : {c} ({d}%)',
				},
				legend: {},
				series: [
					{
						name: '应用资金来源百分比',
						type: 'pie',
						radius: ['30%', '50%'],
						label: {
							formatter: '{b}:{@d}',
						},
						data: data,
					},
				],
			};
			sourceChart.setOption(option);
		}
		function initBudget(month: string[], seriesData: Array<Object>) {
			//应用总投资与应用年度预算
			budgetChart = budgetChart || echarts.init(budgetRef.value);
			let option = {
				title: {
					text: '单位：万元',
					left: 'right',
					textStyle: {
						fontSize: 14,
					},
				},
				legend: {
					top: 'bottom',
				},
				tooltip: {},
				xAxis: {
					boundaryGap: false,
					type: 'category',
					data: month,
					axisLabel: {
						interval: 'auto',
						rotate: 35,
					},
				},
				grid: {
					containLabel: true,
				},
				yAxis: {
					type: 'value',
				},
				series: seriesData,
			};
			budgetChart.setOption(option);
		}
		function initLevel(month: string[], seriesData: Array<Object>) {
			//建设层级
			levelChart = levelChart || echarts.init(levelRef.value);
			let option = {
				legend: {
					top: 'bottom',
				},
				tooltip: {},
				xAxis: {
					type: 'category',
					data: month,
					axisLabel: {
						interval: 'auto',
						rotate: 35,
					},
				},
				grid: {
					containLabel: true,
				},
				yAxis: {
					type: 'value',
				},
				series: seriesData,
			};
			levelChart.setOption(option);
		}
		let appTotal = ref(0);
		function chrengParms(data: any) {
			// let param = { ...data, responsibleDeptId: data?.responsibleDeptId?.length > 0 ? data.responsibleDeptId.join(',') : null };
			let param = {
				...data,
				responsibleDeptId: data?.responsibleDeptId?.length > 0 ? data.responsibleDeptId[data?.responsibleDeptId?.length - 1] : null,
			};
			return param;
		}
		function getNumberFun() {
			return new Promise((resolve) => {
				let params = toRaw(hyFormRef.value.hyForm);
				let param = chrengParms(params);
				getSensitiveCount(param)
					.then((res) => {
						resolve(res);
					})
					.catch(() => {
						resolve({});
					});
			});
		}
		function getPercentFun() {
			return new Promise((resolve) => {
				let params = toRaw(hyFormRef.value.hyForm);
				let param = chrengParms(params);
				getSensitiveHierarchy(param)
					.then((res) => {
						resolve(res);
					})
					.catch(() => {
						resolve({});
					});
			});
		}
		function getSensitive() {
			return new Promise((resolve) => {
				let params = toRaw(hyFormRef.value.hyForm);
				let param = chrengParms(params);
				getSensitiveModeCount(param)
					.then((res) => {
						resolve(res);
					})
					.catch(() => {
						resolve({});
					});
			});
		}

		async function getData() {
			let year = hyFormRef.value.hyForm.year;
			if (!year) {
				hyFormRef.value.hyForm.year = defaultYear; //如果年份没有默认为今年
			}

			loading.value = true;
			const data: any = await Promise.all([getNumberFun(), getPercentFun(), getSensitive()]);
			console.log('---------------------------');
			if (data[0] && data[0].ok) {
				let res = data[0];
				appTotal.value = res.data?.appTotal;
				let appData = [
					//应用数量
					{ value: res.data?.developNumber, name: '开发应用' },
					{ value: res.data?.devOpsNumber, name: '运维应用' },
				];
				let domainData = [
					//领域数量
					{ value: res.data?.partyBuilding, name: '数字党建' },
					{ value: res.data?.governmentAffairs, name: '数字政务' },
					{ value: res.data?.culture, name: '数字文化' },
					{ value: res.data?.economy, name: '数字经济' },
					{ value: res.data?.legal, name: '数字法治' },
					{ value: res.data?.smartGovernance, name: '基层智治' },
					{ value: res.data?.social, name: '数字社会' },
				];
				let sourceData = [
					//资金来源
					{ value: res.data?.centerAmount, name: '中央财政资金' },
					{ value: res.data?.cityAmount, name: '市级财政资金' },
					{ value: res.data?.districtAmount, name: '区县财政资金' },
					{ value: res.data?.deptAmount, name: '部门自筹资金' },
					{ value: res.data?.bankAmount, name: '银行贷款等投资' },
					{ value: res.data?.otherAmount, name: '其他' },
				];
				initApp(appData);
				initDomain(domainData);
				initSource(sourceData);
			}
			if (data[1] && data[1].ok) {
				let _res = data[1];
				let dataMonth: any = [];
				let yearData: string[] = []; //应用年度预算（万元）
				let totalData: string[] = []; //应用总投资（万元）
				_res.data.forEach((item) => {
					dataMonth.push({
						value: item.month + '月',
						textStyle: {
							fontSize: 10,
						},
					});
					yearData.push(item.yearBudgetTotal);
					totalData.push(item.totalBudgetTotal);
				});
				let seriesData = [
					{ name: '应用总投资（万元）', data: totalData, type: 'line' },
					{ name: '应用年度预算（万元）', data: yearData, type: 'line' },
				];
				initBudget(dataMonth, seriesData);
			}
			if (data[2] && data[2].ok) {
				let rs = data[2];
				let dataMonth: any = []; //月份
				let nationalData: string[] = []; //国家
				let provincialData: string[] = []; //省
				let cityData: string[] = []; //市
				let countyData: string[] = []; //区县
				let townData: string[] = []; //街镇
				rs.data.forEach((item) => {
					dataMonth.push({
						value: item.month + '月',
						textStyle: {
							fontSize: 10,
						},
					});
					nationalData.push(item.national);
					provincialData.push(item.provincial);
					cityData.push(item.city);
					countyData.push(item.county);
					townData.push(item.town);
				});
				let series = [
					{ name: '国家', data: nationalData, type: 'bar' },
					{ name: '省级', data: provincialData, type: 'bar' },
					{ name: '市级', data: cityData, type: 'bar' },
					{ name: '区县', data: countyData, type: 'bar' },
					{ name: '街道', data: townData, type: 'bar' },
				];
				initLevel(dataMonth, series);
			}
			loading.value = false;
			if (!resizeObserver) {
				resizeObserver = new ResizeObserver((entries) => {
					entries.forEach(() => {
						handleResize();
					});
				});
				resizeObserver.observe(container.value);
			}
		}

		function handleReset() {
			hyFormRef.value.hyForm.year = defaultYear;
			hyFormRef.value.hyForm.responsibleDeptId = null;
			getData();
		}
		function getDeptData() {
			deptTree({}).then((res) => {
				hyFormFields.value.responsibleDeptId.options = res.data;
			});
		}
		window.onresize = function () {
			handleResize();
		};
		const handleResize = debounce(function () {
			domainChart && domainChart.resize();
			appChart && appChart.resize();
			sourceChart && sourceChart.resize();
			budgetChart && budgetChart.resize();
			levelChart && levelChart.resize();
		}, 100);
		onMounted(() => {
			getData();
			getDeptData();
		});

		onBeforeUnmount(() => {
			if (resizeObserver) {
				resizeObserver.disconnect();
			}
		});
		return {
			loading,
			container,
			hyFormRef,
			searchConfig,
			searchDefault,
			hyFormFields,
			levelRef,
			budgetRef,
			sourceRef,
			appRef,
			domainRef,
			appTotal,
			getData,
			handleReset,
		};
	},
});
</script>

<style scoped lang="scss">
.statics-container {
	height: auto;
	.echart-area {
		display: flex;
		flex-wrap: wrap;
		gap: 10px;
		> div {
			width: 32%;
			.chart-box {
				width: 100%;
				height: 300px;
			}
		}
		.app-count {
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			font-size: 28px;
			height: 300px;
			gap: 10px;
		}
	}
	:deep(.el-input__suffix-inner el-input__icon) {
		display: none;
	}
}
</style>
